package codeine;

import java.util.List;
import java.util.Map;

import codeine.configuration.directory.DiscoveredProjectJson;
import codeine.configuration.directory.PeerStatusJson;
import codeine.configuration.directory.PeersListJson;
import codeine.jsons.nodes.NodeJson;
import codeine.jsons.nodes.NodeListJson;
import codeine.jsons.project.ProjectJson;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

public class NodesManagerServer{

	private Map<String, NodeListJson> project_peerToNode = Maps.newHashMap();
	
	public List<NodeJson> getNodes(ProjectJson project, String peerNameNoPort) {
		String key = project.name() + "_" + peerNameNoPort;
		NodeListJson nodeListJson = project_peerToNode.get(key);
		if (null == nodeListJson){
			return Lists.newArrayList();
		}
		return nodeListJson.nodes();
	}

	public void updateAllNodes(PeersListJson peers) {
		project_peerToNode = createNewMap(peers);
	}

	private Map<String, NodeListJson> createNewMap(PeersListJson peers) {
		Map<String, NodeListJson> $ = Maps.newHashMap();
		for (PeerStatusJson peerStatus : peers.peers().values()) {
			List<DiscoveredProjectJson> projects = peerStatus.projects();
			for (DiscoveredProjectJson discoveredProjectJson : projects) {
				String key = discoveredProjectJson.project_name() + "_" + peerStatus.host();
				NodeListJson nodeListJson = $.get(key);
				if (null == nodeListJson){
					nodeListJson = new NodeListJson();
					$.put(key, nodeListJson);
				}
				nodeListJson.addAll(discoveredProjectJson.nodes());
			}
		}
		return $;
	}

	

	
}
